package com.study.demo.ui.thread;

import android.app.Activity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridLayout;
import android.widget.TextView;

import com.study.demo.R;
import com.study.demo.db.CustomThread;
import com.study.demo.db.ReadThread;
import com.study.demo.greendao.ReadThreadDao;
import com.study.demo.ui.content.ContentActivity;
import com.study.demo.util.ResourceUtil;
import com.study.demo.util.SettingPrefUtil;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by sll on 2016/3/9.
 */
public class ThreadListAdapter extends RecyclerView.Adapter<ThreadListAdapter.ViewHolder> {


    private Activity mActivity;
    private ReadThreadDao mReadThreadDao;

    @Inject
    public ThreadListAdapter(Activity mActivity, ReadThreadDao mReadThreadDao) {
        this.mActivity = mActivity;
        this.mReadThreadDao = mReadThreadDao;
        customThreads = Collections.emptyList();
    }

    private List<CustomThread> customThreads;

    public void bind(List<CustomThread> customThreads) {
        this.customThreads = customThreads;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v =
                LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_thread, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final CustomThread customThread = customThreads.get(position);
        holder.customThread = customThread;
        holder.tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, SettingPrefUtil.getTitleSize(mActivity));
        holder.tvTitle.setText(Html.fromHtml(customThread.getTitle()));
        if (customThread.getLightReply() != null && customThread.getLightReply() > 0) {
            holder.tvLight.setText(String.valueOf(customThread.getLightReply()));
            holder.tvLight.setVisibility(View.VISIBLE);
        } else {
            holder.tvLight.setVisibility(View.GONE);
        }
        holder.tvReply.setText(customThread.getReplies());

        holder.tvSingleTime.setVisibility(View.VISIBLE);
        holder.tvSummary.setVisibility(View.GONE);
        holder.grid.setVisibility(View.GONE);
        if (customThread.getForum() != null) {
            holder.tvSingleTime.setText(customThread.getForum().getName());
        } else {
            holder.tvSingleTime.setText(customThread.getTime());
        }
        Observable.just(customThread.getTid())
                .map((tid) ->
                        mReadThreadDao.queryBuilder().where(ReadThreadDao.Properties.Tid.eq(tid)).count() > 0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        holder.tvTitle.setTextColor(
                                ResourceUtil.getThemeAttrColor(mActivity, android.R.attr.textColorSecondary));
                    } else {
                        holder.tvTitle.setTextColor(
                                ResourceUtil.getThemeAttrColor(mActivity, android.R.attr.textColorPrimary));
                    }
                });
        showItemAnim(holder.cardView, position);
    }

    private int mLastPosition = -1;

    public void showItemAnim(final View view, final int position) {
        if (position > mLastPosition) {
            Animation animation = AnimationUtils.loadAnimation(view.getContext(), R.anim.item_bottom_in);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    view.setAlpha(1);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            view.startAnimation(animation);
            mLastPosition = position;
        }
    }

    @Override
    public int getItemCount() {
        return customThreads.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tvTitle)
        TextView tvTitle;
        @BindView(R.id.tvSummary)
        TextView tvSummary;
        @BindView(R.id.grid)
        GridLayout grid;
        @BindView(R.id.tvSingleTime)
        TextView tvSingleTime;
        @BindView(R.id.tvReply)
        TextView tvReply;
        @BindView(R.id.tvLight)
        TextView tvLight;
        @BindView(R.id.cardView)
        CardView cardView;

        CustomThread customThread;

        @OnClick(R.id.llThreadItem)
        void llThreadItemClick() {
            Observable.just(customThread.getTid())
                    .doOnNext(tid -> {
                        mReadThreadDao.queryBuilder()
                                .where(ReadThreadDao.Properties.Tid.eq(tid))
                                .buildDelete()
                                .executeDeleteWithoutDetachingEntities();
                        ReadThread readThread = new ReadThread(null, tid);
                        mReadThreadDao.insert(readThread);
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(s -> {
                        notifyDataSetChanged();
                        ContentActivity.startActivity(mActivity, customThread.getFid(), customThread.getTid(), "", 1);
                    });
        }

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
